<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Str;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Requests\CaptchaRequest;

class CaptchasController extends Controller
{
	public function store(CaptchaBuilder $captchaBuilder)
    {
	    $lock = Cache::lock('send_captcha', 15);

	    try {

		    if (! $lock->get()) fail('请稍后重试');

		    $request = app(CaptchaRequest::class);

		    $key = 'captcha-'.Str::random(15);
		    $phone = $request->phone;

		    $captcha = $captchaBuilder->build();
		    $expiredAt = now()->addMinutes(2);

		    Cache::put($key, ['phone' => $phone, 'code' => $captcha->getPhrase()], $expiredAt);

		    $result = [
			    'captcha_key' => $key,
			    'expired_at' => $expiredAt->toDateTimeString(),
			    'captcha_image_content' => $captcha->inline()
		    ];

	    } finally {
	    	$lock->release();
	    }

	    return response()->json($result)->setStatusCode(201);
    }
}
